from zz import zz_code, zz_dingtalk, zz_return, zz_log, zz_str
import requests

log = zz_log.of()


def run():
    # token格式
    # name | wx_from | wx_from_enc & name2 | wx_from2 | wx_from_enc2
    token = zz_code.env("JM_TOKEN")
    token_arr = zz_str.split2(token, '&', '|')
    log.info(token_arr)
    if token_arr is None:
        log.error('未配置JM_TOKEN')
        return

    log_msg = '**新星球积分签到** \n\n'
    for item in token_arr:
        handle = Handle(item[0], item[1], item[2], 'app.english')

        log_msg_one = handle.run_one()
        log_msg += log_msg_one + "\n\n"

    log.info(log_msg)
    zz_dingtalk.send_markdown(log_msg, "jm")


class Handle:
    def __init__(self, name, wx_from, wx_from_enc, site_id):
        self.name = name
        self.wx_from = wx_from
        self.wx_from_enc = wx_from_enc
        self.site_id = site_id

        self.root = 'https://sapi.wx.xiao-bo.com/'
        if site_id == 'app.english':
            self.root = 'https://sapi.uat.xiao-bo.com/'

    def run_one(self):
        if zz_str.is_null_or_empty(self.name) or zz_str.is_null_or_empty(self.wx_from) or zz_str.is_null_or_empty(
                self.wx_from_enc):
            return "缺少参数"
        log_msg = self.name + " \n"

        r = self.qian()
        if r.ok() and zz_str.is_null_or_empty(r.get_errmsg()):
            r.set_errmsg("签到成功")

        log_msg += f"{r.get_errmsg()}"

        return log_msg

    def get_wx_from_query(self):
        return f"wx_from={self.wx_from}&wx_from_enc={self.wx_from_enc}";

    def get_headers(self):
        headers = {
            "apixAuth": '1',
        }
        user_agent = zz_code.env("USER_AGENT")
        if zz_str.has_any_text(user_agent):
            headers['User-Agent'] = user_agent
        return headers

    # 新星球积分签到
    def qian(self):
        api_url = f"{self.root}__api_java__/z_app/sign_in_b/web/zz_api__api__new__sign?site_id={self.site_id}&wx_word=sign_in10001000&{self.get_wx_from_query()}"

        headers = self.get_headers()
        log.debug(api_url)
        res = requests.get(api_url, headers=headers)
        r = self.to_return(res.content)

        return r

    def to_return(self, content) -> zz_return.Return:
        log.debug(content)
        try:
            r = zz_return.parse(content)
            # errcode = r.get_data('code')
            # errmsg = r.get_data('message')
            # r.set_errmsg(errmsg)
            # r.set_errcode(errcode)
        except Exception as ex:
            log.error(ex)
            r = zz_return.of(123456, ex)
        log.info(f"return: {r.to_json()}")

        return r


if __name__ == '__main__':
    run()
